<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">
<meta name="referrer" content="same-origin">
<meta name="referrer" content="no-referrer" />








<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="RocketMQ之旅," />










<meta name="description" content="从官方示例开始&amp;emsp;&amp;emsp;先从一个官网的同步消息发送示例开始：123456789101112131415161718192021222324public class SyncProducer &amp;#123;    public static void main(String[] args) throws Exception &amp;#123;        //Instantiate with">
<meta name="keywords" content="RocketMQ之旅">
<meta property="og:type" content="article">
<meta property="og:title" content="RocketMQ之旅（三）client之Producer">
<meta property="og:url" content="http://yoursite.com/2018/10/25/RocketMQ之旅（三）client之Producer/index.html">
<meta property="og:site_name" content="矩阵编程">
<meta property="og:description" content="从官方示例开始&amp;emsp;&amp;emsp;先从一个官网的同步消息发送示例开始：123456789101112131415161718192021222324public class SyncProducer &amp;#123;    public static void main(String[] args) throws Exception &amp;#123;        //Instantiate with">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://ww1.sinaimg.cn/large/639cfad5gy1fw115wb6y0j20p20eodgi.jpg">
<meta property="og:updated_time" content="2019-10-24T16:22:00.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="RocketMQ之旅（三）client之Producer">
<meta name="twitter:description" content="从官方示例开始&amp;emsp;&amp;emsp;先从一个官网的同步消息发送示例开始：123456789101112131415161718192021222324public class SyncProducer &amp;#123;    public static void main(String[] args) throws Exception &amp;#123;        //Instantiate with">
<meta name="twitter:image" content="http://ww1.sinaimg.cn/large/639cfad5gy1fw115wb6y0j20p20eodgi.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2018/10/25/RocketMQ之旅（三）client之Producer/"/>





  <title>RocketMQ之旅（三）client之Producer | 矩阵编程</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?7d29e6fba8e07d1a8af2414a20e5f2a6";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">矩阵编程</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-主页">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-主页"></i> <br />
            
            主页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-分类"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-所有文章">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-文章"></i> <br />
            
            所有文章
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2018/10/25/RocketMQ之旅（三）client之Producer/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="matrix">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="矩阵编程">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">RocketMQ之旅（三）client之Producer</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-10-25T13:49:21+08:00">
                2018-10-25
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/RocketMQ之旅/" itemprop="url" rel="index">
                    <span itemprop="name">RocketMQ之旅</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2018/10/25/RocketMQ之旅（三）client之Producer/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count"
                        data-disqus-identifier="2018/10/25/RocketMQ之旅（三）client之Producer/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h3 id="从官方示例开始"><a href="#从官方示例开始" class="headerlink" title="从官方示例开始"></a>从官方示例开始</h3><p>&emsp;&emsp;先从一个官网的同步消息发送示例开始：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SyncProducer</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        <span class="comment">//Instantiate with a producer group name.</span></span><br><span class="line">        DefaultMQProducer producer = <span class="keyword">new</span></span><br><span class="line">            DefaultMQProducer(<span class="string">"please_rename_unique_group_name"</span>);</span><br><span class="line">        <span class="comment">// Specify name server addresses.</span></span><br><span class="line">        producer.setNamesrvAddr(<span class="string">"localhost:9876"</span>);</span><br><span class="line">        <span class="comment">//Launch the instance.</span></span><br><span class="line">        producer.start();</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">100</span>; i++) &#123;</span><br><span class="line">            <span class="comment">//Create a message instance, specifying topic, tag and message body.</span></span><br><span class="line">            Message msg = <span class="keyword">new</span> Message(<span class="string">"TopicTest"</span> <span class="comment">/* Topic */</span>,</span><br><span class="line">                <span class="string">"TagA"</span> <span class="comment">/* Tag */</span>,</span><br><span class="line">                (<span class="string">"Hello RocketMQ "</span> +</span><br><span class="line">                    i).getBytes(RemotingHelper.DEFAULT_CHARSET) <span class="comment">/* Message body */</span></span><br><span class="line">            );</span><br><span class="line">            <span class="comment">//Call send message to deliver message to one of brokers.</span></span><br><span class="line">            SendResult sendResult = producer.send(msg);</span><br><span class="line">            System.out.printf(<span class="string">"%s%n"</span>, sendResult);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//Shut down once the producer instance is not longer in use.</span></span><br><span class="line">        producer.shutdown();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<a id="more"></a>
<p>DefaultMQProducer的类图结构很简单：<br><img src="http://ww1.sinaimg.cn/large/639cfad5gy1fw115wb6y0j20p20eodgi.jpg" alt><br>直接看DefaultMQProducer的构造函数：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">DefaultMQProducer</span><span class="params">(<span class="keyword">final</span> String producerGroup, RPCHook rpcHook)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">this</span>.producerGroup = producerGroup;</span><br><span class="line">    defaultMQProducerImpl = <span class="keyword">new</span> DefaultMQProducerImpl(<span class="keyword">this</span>, rpcHook);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>producerGroup相当于具有相同属性的一组Producer，对于事务消息的处理有很大作用，非事务消息没什么关系。DefaultMQProducerImpl这名字取得一眼看便知是DefaultMQProducer的实现，不过DefaultMQProducerImpl并不继承于DefaultMQProducer。</p>
<h3 id="启动Producer"><a href="#启动Producer" class="headerlink" title="启动Producer"></a>启动Producer</h3><p>继续看DefaultMQProducer的<strong>start()</strong>是如何初始化的：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">start</span><span class="params">()</span> <span class="keyword">throws</span> MQClientException </span>&#123;</span><br><span class="line">    <span class="keyword">this</span>.defaultMQProducerImpl.start();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>调用的是DefaultMQProducerImpl的<strong>start()</strong>：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">start</span><span class="params">(<span class="keyword">final</span> <span class="keyword">boolean</span> startFactory)</span> <span class="keyword">throws</span> MQClientException </span>&#123;</span><br><span class="line">    <span class="keyword">switch</span> (<span class="keyword">this</span>.serviceState) &#123;</span><br><span class="line">        <span class="keyword">case</span> CREATE_JUST:</span><br><span class="line">            <span class="keyword">this</span>.serviceState = ServiceState.START_FAILED;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">this</span>.checkConfig();</span><br><span class="line"></span><br><span class="line">            <span class="keyword">if</span> (!<span class="keyword">this</span>.defaultMQProducer.getProducerGroup().equals(MixAll.CLIENT_INNER_PRODUCER_GROUP)) &#123;</span><br><span class="line">                <span class="keyword">this</span>.defaultMQProducer.changeInstanceNameToPID();</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">this</span>.mQClientFactory = MQClientManager.getInstance().getAndCreateMQClientInstance(<span class="keyword">this</span>.defaultMQProducer, rpcHook);</span><br><span class="line"></span><br><span class="line">            <span class="keyword">boolean</span> registerOK = mQClientFactory.registerProducer(<span class="keyword">this</span>.defaultMQProducer.getProducerGroup(), <span class="keyword">this</span>);</span><br><span class="line">            <span class="keyword">if</span> (!registerOK) &#123;</span><br><span class="line">                <span class="keyword">this</span>.serviceState = ServiceState.CREATE_JUST;</span><br><span class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> MQClientException(<span class="string">"The producer group["</span> + <span class="keyword">this</span>.defaultMQProducer.getProducerGroup()</span><br><span class="line">                    + <span class="string">"] has been created before, specify another name please."</span> + FAQUrl.suggestTodo(FAQUrl.GROUP_NAME_DUPLICATE_URL),</span><br><span class="line">                    <span class="keyword">null</span>);</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">this</span>.topicPublishInfoTable.put(<span class="keyword">this</span>.defaultMQProducer.getCreateTopicKey(), <span class="keyword">new</span> TopicPublishInfo());</span><br><span class="line"></span><br><span class="line">            <span class="keyword">if</span> (startFactory) &#123;</span><br><span class="line">                mQClientFactory.start();</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            log.info(<span class="string">"the producer [&#123;&#125;] start OK. sendMessageWithVIPChannel=&#123;&#125;"</span>, <span class="keyword">this</span>.defaultMQProducer.getProducerGroup(),</span><br><span class="line">                <span class="keyword">this</span>.defaultMQProducer.isSendMessageWithVIPChannel());</span><br><span class="line">            <span class="keyword">this</span>.serviceState = ServiceState.RUNNING;</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        <span class="keyword">case</span> RUNNING:</span><br><span class="line">        <span class="keyword">case</span> START_FAILED:</span><br><span class="line">        <span class="keyword">case</span> SHUTDOWN_ALREADY:</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> MQClientException(<span class="string">"The producer service state not OK, maybe started once, "</span></span><br><span class="line">                + <span class="keyword">this</span>.serviceState</span><br><span class="line">                + FAQUrl.suggestTodo(FAQUrl.CLIENT_SERVICE_NOT_OK),</span><br><span class="line">                <span class="keyword">null</span>);</span><br><span class="line">        <span class="keyword">default</span>:</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">this</span>.mQClientFactory.sendHeartbeatToAllBrokerWithLock();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<ol>
<li>初始serviceState为CREATE_JUST，先检测一下producerGroup是否合法，如果producerGroup为CLIENT_INNER_PRODUCER_GROUP，使用pid作为producerGroup。</li>
<li><p>MQClientManager初始化一个MQClientInstance实例，调用MQClientInstance的<strong>start()</strong><br>：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">start</span><span class="params">()</span> <span class="keyword">throws</span> MQClientException </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">synchronized</span> (<span class="keyword">this</span>) &#123;</span><br><span class="line">        <span class="keyword">switch</span> (<span class="keyword">this</span>.serviceState) &#123;</span><br><span class="line">            <span class="keyword">case</span> CREATE_JUST:</span><br><span class="line">                <span class="keyword">this</span>.serviceState = ServiceState.START_FAILED;</span><br><span class="line">                <span class="comment">// If not specified,looking address from name server</span></span><br><span class="line">                <span class="keyword">if</span> (<span class="keyword">null</span> == <span class="keyword">this</span>.clientConfig.getNamesrvAddr()) &#123;</span><br><span class="line">                    <span class="keyword">this</span>.mQClientAPIImpl.fetchNameServerAddr();</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="comment">// Start request-response channel</span></span><br><span class="line">                <span class="keyword">this</span>.mQClientAPIImpl.start();</span><br><span class="line">                <span class="comment">// Start various schedule tasks</span></span><br><span class="line">                <span class="keyword">this</span>.startScheduledTask();</span><br><span class="line">                <span class="comment">// Start pull service</span></span><br><span class="line">                <span class="keyword">this</span>.pullMessageService.start();</span><br><span class="line">                <span class="comment">// Start rebalance service</span></span><br><span class="line">                <span class="keyword">this</span>.rebalanceService.start();</span><br><span class="line">                <span class="comment">// Start push service</span></span><br><span class="line">                <span class="keyword">this</span>.defaultMQProducer.getDefaultMQProducerImpl().start(<span class="keyword">false</span>);</span><br><span class="line">                log.info(<span class="string">"the client factory [&#123;&#125;] start OK"</span>, <span class="keyword">this</span>.clientId);</span><br><span class="line">                <span class="keyword">this</span>.serviceState = ServiceState.RUNNING;</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> RUNNING:</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> SHUTDOWN_ALREADY:</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> START_FAILED:</span><br><span class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> MQClientException(<span class="string">"The Factory object["</span> + <span class="keyword">this</span>.getClientId() + <span class="string">"] has been created before, and failed."</span>, <span class="keyword">null</span>);</span><br><span class="line">            <span class="keyword">default</span>:</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>做了下面这几件事：</p>
<ul>
<li>如果Producer未设置namesrvAddr，http GET 请求动态获取。</li>
<li>调用remoting模块中的NettyRemotingClient的start()，配置相应的客户端Channel，此时还未调用远程连接。</li>
<li><strong>startScheduledTask()</strong>启动一些定时任务：每2分钟http请求获取namesrvAddr；定时从NameServer获取Topic路由信息；定时发送心跳请求Broker，并清除下线的Broker；定时保存消费进度；每分钟调整消费线程池的核心线程数（代码被注释了，暂未实现）</li>
<li>启动消息拉取的线程、消息拉取负载均衡线程。</li>
<li>启动内部的DefaultMQProducer。</li>
</ul>
</li>
<li>给Broker发送心跳，不过首次启动由于<strong>brokerAddrTable</strong>为空，所以此处其实不会发送心跳数据。</li>
</ol>
<h3 id="发送消息"><a href="#发送消息" class="headerlink" title="发送消息"></a>发送消息</h3><p>&emsp;&emsp;<strong>DefaultMQProducer</strong>的<strong>start()</strong>分析完毕，继续看producer是如何发送消息的：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> SendResult <span class="title">send</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">    Message msg)</span> <span class="keyword">throws</span> MQClientException, RemotingException, MQBrokerException, InterruptedException </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">this</span>.defaultMQProducerImpl.send(msg);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>依然是DefaultMQProducerImpl的<strong>send(msg)</strong>:<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> SendResult <span class="title">send</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">    Message msg)</span> <span class="keyword">throws</span> MQClientException, RemotingException, MQBrokerException, InterruptedException </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> send(msg, <span class="keyword">this</span>.defaultMQProducer.getSendMsgTimeout());</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">public</span> SendResult <span class="title">send</span><span class="params">(Message msg,</span></span></span><br><span class="line"><span class="function"><span class="params">    <span class="keyword">long</span> timeout)</span> <span class="keyword">throws</span> MQClientException, RemotingException, MQBrokerException, InterruptedException </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">this</span>.sendDefaultImpl(msg, CommunicationMode.SYNC, <span class="keyword">null</span>, timeout);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p><strong>sendDefaultImpl</strong>方法很长，这里为了方便查看，省略了错误分支的代码，只精简出一个主干：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> SendResult <span class="title">sendDefaultImpl</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">    Message msg,</span></span></span><br><span class="line"><span class="function"><span class="params">    <span class="keyword">final</span> CommunicationMode communicationMode,</span></span></span><br><span class="line"><span class="function"><span class="params">    <span class="keyword">final</span> SendCallback sendCallback,</span></span></span><br><span class="line"><span class="function"><span class="params">    <span class="keyword">final</span> <span class="keyword">long</span> timeout</span></span></span><br><span class="line"><span class="function"><span class="params">)</span> <span class="keyword">throws</span> MQClientException, RemotingException, MQBrokerException, InterruptedException </span>&#123;</span><br><span class="line">    <span class="keyword">this</span>.makeSureStateOK();</span><br><span class="line">    Validators.checkMessage(msg, <span class="keyword">this</span>.defaultMQProducer);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">final</span> <span class="keyword">long</span> invokeID = random.nextLong();</span><br><span class="line">    <span class="keyword">long</span> beginTimestampFirst = System.currentTimeMillis();</span><br><span class="line">    <span class="keyword">long</span> beginTimestampPrev = beginTimestampFirst;</span><br><span class="line">    <span class="keyword">long</span> endTimestamp = beginTimestampFirst;</span><br><span class="line">    TopicPublishInfo topicPublishInfo = <span class="keyword">this</span>.tryToFindTopicPublishInfo(msg.getTopic());</span><br><span class="line">    <span class="keyword">if</span> (topicPublishInfo != <span class="keyword">null</span> &amp;&amp; topicPublishInfo.ok()) &#123;</span><br><span class="line">        <span class="keyword">boolean</span> callTimeout = <span class="keyword">false</span>;</span><br><span class="line">        MessageQueue mq = <span class="keyword">null</span>;</span><br><span class="line">        Exception exception = <span class="keyword">null</span>;</span><br><span class="line">        SendResult sendResult = <span class="keyword">null</span>;</span><br><span class="line">        <span class="keyword">int</span> timesTotal = communicationMode == CommunicationMode.SYNC ? <span class="number">1</span> + <span class="keyword">this</span>.defaultMQProducer.getRetryTimesWhenSendFailed() : <span class="number">1</span>;</span><br><span class="line">        <span class="keyword">int</span> times = <span class="number">0</span>;</span><br><span class="line">        String[] brokersSent = <span class="keyword">new</span> String[timesTotal];</span><br><span class="line">        <span class="keyword">for</span> (; times &lt; timesTotal; times++) &#123;</span><br><span class="line">            String lastBrokerName = <span class="keyword">null</span> == mq ? <span class="keyword">null</span> : mq.getBrokerName();</span><br><span class="line">            MessageQueue mqSelected = <span class="keyword">this</span>.selectOneMessageQueue(topicPublishInfo, lastBrokerName);</span><br><span class="line">            <span class="keyword">if</span> (mqSelected != <span class="keyword">null</span>) &#123;</span><br><span class="line">                mq = mqSelected;</span><br><span class="line">                brokersSent[times] = mq.getBrokerName();</span><br><span class="line">                <span class="keyword">try</span> &#123;</span><br><span class="line">                    beginTimestampPrev = System.currentTimeMillis();</span><br><span class="line">                    <span class="keyword">long</span> costTime = beginTimestampPrev - beginTimestampFirst;</span><br><span class="line">                    <span class="keyword">if</span> (timeout &lt; costTime) &#123;</span><br><span class="line">                        callTimeout = <span class="keyword">true</span>;</span><br><span class="line">                        <span class="keyword">break</span>;</span><br><span class="line">                    &#125;</span><br><span class="line"></span><br><span class="line">                    sendResult = <span class="keyword">this</span>.sendKernelImpl(msg, mq, communicationMode, sendCallback, topicPublishInfo, timeout - costTime);</span><br><span class="line">                    endTimestamp = System.currentTimeMillis();</span><br><span class="line">                    <span class="keyword">this</span>.updateFaultItem(mq.getBrokerName(), endTimestamp - beginTimestampPrev, <span class="keyword">false</span>);</span><br><span class="line">                    <span class="keyword">switch</span> (communicationMode) &#123;</span><br><span class="line">                        <span class="keyword">case</span> ASYNC:</span><br><span class="line">                            <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">                        <span class="keyword">case</span> ONEWAY:</span><br><span class="line">                            <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">                        <span class="keyword">case</span> SYNC:</span><br><span class="line">                            <span class="keyword">if</span> (sendResult.getSendStatus() != SendStatus.SEND_OK) &#123;</span><br><span class="line">                                <span class="keyword">if</span> (<span class="keyword">this</span>.defaultMQProducer.isRetryAnotherBrokerWhenNotStoreOK()) &#123;</span><br><span class="line">                                    <span class="keyword">continue</span>;</span><br><span class="line">                                &#125;</span><br><span class="line">                            &#125;</span><br><span class="line"></span><br><span class="line">                            <span class="keyword">return</span> sendResult;</span><br><span class="line">                        <span class="keyword">default</span>:</span><br><span class="line">                            <span class="keyword">break</span>;</span><br><span class="line">                    &#125;</span><br><span class="line">                    <span class="comment">// 省略了catch中的代码...</span></span><br><span class="line">                &#125; <span class="keyword">catch</span> (RemotingException e) &#123;</span><br><span class="line">                &#125; <span class="keyword">catch</span> (MQClientException e) &#123;</span><br><span class="line">                &#125; <span class="keyword">catch</span> (MQBrokerException e) &#123;</span><br><span class="line">                &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (sendResult != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> sendResult;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 以下省略错误分支的代码...</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">throw</span> <span class="keyword">new</span> MQClientException(<span class="string">"No route info of this topic, "</span> + msg.getTopic() + FAQUrl.suggestTodo(FAQUrl.NO_TOPIC_ROUTE_INFO),</span><br><span class="line">        <span class="keyword">null</span>).setResponseCode(ClientErrorCode.NOT_FOUND_TOPIC_EXCEPTION);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<ol>
<li>说一下<strong>CommunicationMode</strong>参数，这是一个枚举，有三种类型：SYNC、ASYNC、ONEWAY，分别对应三种消息发送模式：同步、异步、单向发送（无需等待应答）。</li>
<li><strong>tryToFindTopicPublishInfo()</strong>寻找当前Topic的路由信息，这部分放后面再看。如果Topic路由会直接抛出异常。</li>
<li>SYNC会有一个重试机制，重试次数为defaultMQProducer中的retryTimesWhenSendFailed。</li>
<li><strong>selectOneMessageQueue()</strong>选择一个消息队列，这部分也放到后面再看。</li>
<li><strong>sendKernelImpl()</strong>应该是发送消息的核心方法了，押后。</li>
<li><strong>updateFaultItem()</strong>是RocketMQ对Broker的延迟容错策略，这里每次调用<strong>sendKernelImpl()</strong>都会计算出本次发送消息耗时。</li>
</ol>
<h4 id="tryToFindTopicPublishInfo寻找路由"><a href="#tryToFindTopicPublishInfo寻找路由" class="headerlink" title="tryToFindTopicPublishInfo寻找路由"></a>tryToFindTopicPublishInfo寻找路由</h4><p>&emsp;&emsp;直接贴tryToFindTopicPublishInfo()代码：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> TopicPublishInfo <span class="title">tryToFindTopicPublishInfo</span><span class="params">(<span class="keyword">final</span> String topic)</span> </span>&#123;</span><br><span class="line">    TopicPublishInfo topicPublishInfo = <span class="keyword">this</span>.topicPublishInfoTable.get(topic);</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">null</span> == topicPublishInfo || !topicPublishInfo.ok()) &#123;</span><br><span class="line">        <span class="keyword">this</span>.topicPublishInfoTable.putIfAbsent(topic, <span class="keyword">new</span> TopicPublishInfo());</span><br><span class="line">        <span class="keyword">this</span>.mQClientFactory.updateTopicRouteInfoFromNameServer(topic);</span><br><span class="line">        topicPublishInfo = <span class="keyword">this</span>.topicPublishInfoTable.get(topic);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (topicPublishInfo.isHaveTopicRouterInfo() || topicPublishInfo.ok()) &#123;</span><br><span class="line">        <span class="keyword">return</span> topicPublishInfo;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">this</span>.mQClientFactory.updateTopicRouteInfoFromNameServer(topic, <span class="keyword">true</span>, <span class="keyword">this</span>.defaultMQProducer);</span><br><span class="line">        topicPublishInfo = <span class="keyword">this</span>.topicPublishInfoTable.get(topic);</span><br><span class="line">        <span class="keyword">return</span> topicPublishInfo;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<ol>
<li>先从缓存的topicPublishInfoTable中寻找TopicPublishInfo信息，如果为空或者TopicPublishInfo中的messageQueueList为空，向topicPublishInfoTable放入一个新建的TopicPublishInfo，然后通过mQClientFactory的<strong>updateTopicRouteInfoFromNameServer()</strong>获取路由信息。</li>
<li>如果TopicPublishInfo缓存不为空，会检测TopicPublishInfo的路由信息和消息队列，如果正确直接返回，否则还是通过mQClientFactory的<strong>updateTopicRouteInfoFromNameServer()</strong>获取路由信息，两次调用最终的方法一致，只是参数有所不同。</li>
</ol>
<p>继续看mQClientFactory的<strong>updateTopicRouteInfoFromNameServer()</strong>：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">updateTopicRouteInfoFromNameServer</span><span class="params">(<span class="keyword">final</span> String topic)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> updateTopicRouteInfoFromNameServer(topic, <span class="keyword">false</span>, <span class="keyword">null</span>);</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">updateTopicRouteInfoFromNameServer</span><span class="params">(<span class="keyword">final</span> String topic, <span class="keyword">boolean</span> isDefault,</span></span></span><br><span class="line"><span class="function"><span class="params">    DefaultMQProducer defaultMQProducer)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (<span class="keyword">this</span>.lockNamesrv.tryLock(LOCK_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)) &#123;</span><br><span class="line">            <span class="comment">// 以下为了方便查看，精简了大段代码，有些不必要的逻辑分支也删掉了，将整个过程分为以下几步：</span></span><br><span class="line">            <span class="comment">// 1. 从nameServer获取该topic的TopicRouteData</span></span><br><span class="line">            topicRouteData = <span class="keyword">this</span>.mQClientAPIImpl.getTopicRouteInfoFromNameServer(topic, <span class="number">1000</span> * <span class="number">3</span>);</span><br><span class="line"></span><br><span class="line">            <span class="comment">// 2. 更新brokerAddrTable，这里缓存了全局的broker地址，发消息的时候需要用</span></span><br><span class="line">             <span class="keyword">for</span> (BrokerData bd : topicRouteData.getBrokerDatas()) &#123;</span><br><span class="line">                <span class="keyword">this</span>.brokerAddrTable.put(bd.getBrokerName(), bd.getBrokerAddrs());</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="comment">// 3. 比对新旧topic的TopicRouteData不同，如果不同将其转换为TopicPublishInfo并分别更新到producerTable和consumerTable。上面tryToFindTopicPublishInfo()中的TopicPublishInfo缓存集合topicPublishInfoTable，就是在这里被更新的。</span></span><br><span class="line">            <span class="comment">// Update Pub info</span></span><br><span class="line">            &#123;</span><br><span class="line">                TopicPublishInfo publishInfo = topicRouteData2TopicPublishInfo(topic, topicRouteData);</span><br><span class="line">                publishInfo.setHaveTopicRouterInfo(<span class="keyword">true</span>);</span><br><span class="line">                Iterator&lt;Entry&lt;String, MQProducerInner&gt;&gt; it = <span class="keyword">this</span>.producerTable.entrySet().iterator();</span><br><span class="line">                <span class="keyword">while</span> (it.hasNext()) &#123;</span><br><span class="line">                    Entry&lt;String, MQProducerInner&gt; entry = it.next();</span><br><span class="line">                    MQProducerInner impl = entry.getValue();</span><br><span class="line">                    <span class="keyword">if</span> (impl != <span class="keyword">null</span>) &#123;</span><br><span class="line">                        impl.updateTopicPublishInfo(topic, publishInfo);</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="comment">// Update sub info</span></span><br><span class="line">            &#123;</span><br><span class="line">                Set&lt;MessageQueue&gt; subscribeInfo = topicRouteData2TopicSubscribeInfo(topic, topicRouteData);</span><br><span class="line">                Iterator&lt;Entry&lt;String, MQConsumerInner&gt;&gt; it = <span class="keyword">this</span>.consumerTable.entrySet().iterator();</span><br><span class="line">                <span class="keyword">while</span> (it.hasNext()) &#123;</span><br><span class="line">                    Entry&lt;String, MQConsumerInner&gt; entry = it.next();</span><br><span class="line">                    MQConsumerInner impl = entry.getValue();</span><br><span class="line">                    <span class="keyword">if</span> (impl != <span class="keyword">null</span>) &#123;</span><br><span class="line">                        impl.updateTopicSubscribeInfo(topic, subscribeInfo);</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="comment">// 4. 拷贝一份TopicRouteData放入topicRouteTable</span></span><br><span class="line">            <span class="comment">// 省略</span></span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            log.warn(<span class="string">"updateTopicRouteInfoFromNameServer tryLock timeout &#123;&#125;ms"</span>, LOCK_TIMEOUT_MILLIS);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">        log.warn(<span class="string">"updateTopicRouteInfoFromNameServer Exception"</span>, e);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>直接看一下mQClientAPIImpl的<strong>getTopicRouteInfoFromNameServer()</strong>是如何获取TopicRouteData的：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> TopicRouteData <span class="title">getTopicRouteInfoFromNameServer</span><span class="params">(<span class="keyword">final</span> String topic, <span class="keyword">final</span> <span class="keyword">long</span> timeoutMillis)</span></span></span><br><span class="line"><span class="function">    <span class="keyword">throws</span> RemotingException, MQClientException, InterruptedException </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> getTopicRouteInfoFromNameServer(topic, timeoutMillis, <span class="keyword">true</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> TopicRouteData <span class="title">getTopicRouteInfoFromNameServer</span><span class="params">(<span class="keyword">final</span> String topic, <span class="keyword">final</span> <span class="keyword">long</span> timeoutMillis,</span></span></span><br><span class="line"><span class="function"><span class="params">    <span class="keyword">boolean</span> allowTopicNotExist)</span> <span class="keyword">throws</span> MQClientException, InterruptedException, RemotingTimeoutException, RemotingSendRequestException, RemotingConnectException </span>&#123;</span><br><span class="line">    GetRouteInfoRequestHeader requestHeader = <span class="keyword">new</span> GetRouteInfoRequestHeader();</span><br><span class="line">    requestHeader.setTopic(topic);</span><br><span class="line"></span><br><span class="line">    RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_ROUTEINTO_BY_TOPIC, requestHeader);</span><br><span class="line"></span><br><span class="line">    RemotingCommand response = <span class="keyword">this</span>.remotingClient.invokeSync(<span class="keyword">null</span>, request, timeoutMillis);</span><br><span class="line">    <span class="keyword">assert</span> response != <span class="keyword">null</span>;</span><br><span class="line">    <span class="keyword">switch</span> (response.getCode()) &#123;</span><br><span class="line">        <span class="keyword">case</span> ResponseCode.TOPIC_NOT_EXIST: &#123;</span><br><span class="line">            <span class="keyword">if</span> (allowTopicNotExist &amp;&amp; !topic.equals(MixAll.AUTO_CREATE_TOPIC_KEY_TOPIC)) &#123;</span><br><span class="line">                log.warn(<span class="string">"get Topic [&#123;&#125;] RouteInfoFromNameServer is not exist value"</span>, topic);</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">case</span> ResponseCode.SUCCESS: &#123;</span><br><span class="line">            <span class="keyword">byte</span>[] body = response.getBody();</span><br><span class="line">            <span class="keyword">if</span> (body != <span class="keyword">null</span>) &#123;</span><br><span class="line">                <span class="keyword">return</span> TopicRouteData.decode(body, TopicRouteData.class);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">default</span>:</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">throw</span> <span class="keyword">new</span> MQClientException(response.getCode(), response.getRemark());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>使用NettyRemotingClient同步发送一个带GET_ROUTEINTO_BY_TOPIC指令的RemotingCommand。至于NameServer怎么处理，可以参照 <strong>RocketMQ之旅（二）namesrv</strong>。</p>
<h4 id="selectOneMessageQueue选择消息队列"><a href="#selectOneMessageQueue选择消息队列" class="headerlink" title="selectOneMessageQueue选择消息队列"></a>selectOneMessageQueue选择消息队列</h4><p>&emsp;&emsp;直接看MQFaultStrategy的<strong>selectOneMessageQueue()</strong>的代码：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> MessageQueue <span class="title">selectOneMessageQueue</span><span class="params">(<span class="keyword">final</span> TopicPublishInfo tpInfo, <span class="keyword">final</span> String lastBrokerName)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.sendLatencyFaultEnable) &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">int</span> index = tpInfo.getSendWhichQueue().getAndIncrement();</span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; tpInfo.getMessageQueueList().size(); i++) &#123;</span><br><span class="line">                <span class="keyword">int</span> pos = Math.abs(index++) % tpInfo.getMessageQueueList().size();</span><br><span class="line">                <span class="keyword">if</span> (pos &lt; <span class="number">0</span>)</span><br><span class="line">                    pos = <span class="number">0</span>;</span><br><span class="line">                MessageQueue mq = tpInfo.getMessageQueueList().get(pos);</span><br><span class="line">                <span class="keyword">if</span> (latencyFaultTolerance.isAvailable(mq.getBrokerName())) &#123;</span><br><span class="line">                    <span class="keyword">if</span> (<span class="keyword">null</span> == lastBrokerName || mq.getBrokerName().equals(lastBrokerName))</span><br><span class="line">                        <span class="keyword">return</span> mq;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">final</span> String notBestBroker = latencyFaultTolerance.pickOneAtLeast();</span><br><span class="line">            <span class="keyword">int</span> writeQueueNums = tpInfo.getQueueIdByBroker(notBestBroker);</span><br><span class="line">            <span class="keyword">if</span> (writeQueueNums &gt; <span class="number">0</span>) &#123;</span><br><span class="line">                <span class="keyword">final</span> MessageQueue mq = tpInfo.selectOneMessageQueue();</span><br><span class="line">                <span class="keyword">if</span> (notBestBroker != <span class="keyword">null</span>) &#123;</span><br><span class="line">                    mq.setBrokerName(notBestBroker);</span><br><span class="line">                    mq.setQueueId(tpInfo.getSendWhichQueue().getAndIncrement() % writeQueueNums);</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="keyword">return</span> mq;</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                latencyFaultTolerance.remove(notBestBroker);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            log.error(<span class="string">"Error occurred when selecting message queue"</span>, e);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> tpInfo.selectOneMessageQueue();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> tpInfo.selectOneMessageQueue(lastBrokerName);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<ol>
<li>selectOneMessageQueue分为两种方式，一种是设置了sendLatencyFaultEnable延迟容错策略，一种未设置。延迟容错LatencyFaultToleranceImpl维护一个发送过的broke队列，记录他们消息发送的延迟时间，并将当前时间+延迟时间记录为startTimestamp，作为判断该broker下一次发送消息的可用性标准，如果下一次发送消息的时间，小于startTimestamp，则该broker还不可用。</li>
<li>sendLatencyFaultEnable为true情况下，选择lastBroker（如果存在上一个发送的broker）的消息队列，且该broke没有加入延迟列表。</li>
<li><p>如果lastBroker（如果有）不可用，使用LatencyFaultToleranceImpl的<strong>pickOneAtLeast()</strong>选择一个broke：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> String <span class="title">pickOneAtLeast</span><span class="params">()</span> </span>&#123;</span><br><span class="line">     <span class="keyword">final</span> Enumeration&lt;FaultItem&gt; elements = <span class="keyword">this</span>.faultItemTable.elements();</span><br><span class="line">     List&lt;FaultItem&gt; tmpList = <span class="keyword">new</span> LinkedList&lt;FaultItem&gt;();</span><br><span class="line">     <span class="keyword">while</span> (elements.hasMoreElements()) &#123;</span><br><span class="line">         <span class="keyword">final</span> FaultItem faultItem = elements.nextElement();</span><br><span class="line">         tmpList.add(faultItem);</span><br><span class="line">     &#125;</span><br><span class="line"></span><br><span class="line">     <span class="keyword">if</span> (!tmpList.isEmpty()) &#123;</span><br><span class="line">         Collections.shuffle(tmpList);</span><br><span class="line"></span><br><span class="line">         Collections.sort(tmpList);</span><br><span class="line"></span><br><span class="line">         <span class="keyword">final</span> <span class="keyword">int</span> half = tmpList.size() / <span class="number">2</span>;</span><br><span class="line">         <span class="keyword">if</span> (half &lt;= <span class="number">0</span>) &#123;</span><br><span class="line">             <span class="keyword">return</span> tmpList.get(<span class="number">0</span>).getName();</span><br><span class="line">         &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">             <span class="keyword">final</span> <span class="keyword">int</span> i = <span class="keyword">this</span>.whichItemWorst.getAndIncrement() % half;</span><br><span class="line">             <span class="keyword">return</span> tmpList.get(i).getName();</span><br><span class="line">         &#125;</span><br><span class="line">     &#125;</span><br><span class="line"></span><br><span class="line">     <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>
<p>将FaultItem列表进行重排序，选择最优列表的一半取模为当前broker。</p>
</li>
<li><p>sendLatencyFaultEnable为false，遍历messageQueueList，选择一个和lastBroker不一样的broker消息队列发送。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> MessageQueue <span class="title">selectOneMessageQueue</span><span class="params">(<span class="keyword">final</span> String lastBrokerName)</span> </span>&#123;</span><br><span class="line">     <span class="keyword">if</span> (lastBrokerName == <span class="keyword">null</span>) &#123;</span><br><span class="line">         <span class="keyword">return</span> selectOneMessageQueue();</span><br><span class="line">     &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">         <span class="keyword">int</span> index = <span class="keyword">this</span>.sendWhichQueue.getAndIncrement();</span><br><span class="line">         <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="keyword">this</span>.messageQueueList.size(); i++) &#123;</span><br><span class="line">             <span class="keyword">int</span> pos = Math.abs(index++) % <span class="keyword">this</span>.messageQueueList.size();</span><br><span class="line">             <span class="keyword">if</span> (pos &lt; <span class="number">0</span>)</span><br><span class="line">                 pos = <span class="number">0</span>;</span><br><span class="line">             MessageQueue mq = <span class="keyword">this</span>.messageQueueList.get(pos);</span><br><span class="line">             <span class="keyword">if</span> (!mq.getBrokerName().equals(lastBrokerName)) &#123;</span><br><span class="line">                 <span class="keyword">return</span> mq;</span><br><span class="line">             &#125;</span><br><span class="line">         &#125;</span><br><span class="line">         <span class="keyword">return</span> selectOneMessageQueue();</span><br><span class="line">     &#125;</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>
<p>当然还有可能还是找不到，那这次也不挑broker了：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> MessageQueue <span class="title">selectOneMessageQueue</span><span class="params">()</span> </span>&#123;</span><br><span class="line">     <span class="keyword">int</span> index = <span class="keyword">this</span>.sendWhichQueue.getAndIncrement();</span><br><span class="line">     <span class="keyword">int</span> pos = Math.abs(index) % <span class="keyword">this</span>.messageQueueList.size();</span><br><span class="line">     <span class="keyword">if</span> (pos &lt; <span class="number">0</span>)</span><br><span class="line">         pos = <span class="number">0</span>;</span><br><span class="line">     <span class="keyword">return</span> <span class="keyword">this</span>.messageQueueList.get(pos);</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>
<p>步骤3如果找不到，也会执行这个方法，取模选择一个MessageQueue。</p>
</li>
</ol>
<h4 id="sendKernelImpl发送消息核心"><a href="#sendKernelImpl发送消息核心" class="headerlink" title="sendKernelImpl发送消息核心"></a>sendKernelImpl发送消息核心</h4><p>直接贴一大段代码：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> SendResult <span class="title">sendKernelImpl</span><span class="params">(<span class="keyword">final</span> Message msg,</span></span></span><br><span class="line"><span class="function"><span class="params">                                    <span class="keyword">final</span> MessageQueue mq,</span></span></span><br><span class="line"><span class="function"><span class="params">                                    <span class="keyword">final</span> CommunicationMode communicationMode,</span></span></span><br><span class="line"><span class="function"><span class="params">                                    <span class="keyword">final</span> SendCallback sendCallback,</span></span></span><br><span class="line"><span class="function"><span class="params">                                    <span class="keyword">final</span> TopicPublishInfo topicPublishInfo,</span></span></span><br><span class="line"><span class="function"><span class="params">                                    <span class="keyword">final</span> <span class="keyword">long</span> timeout)</span> <span class="keyword">throws</span> MQClientException, RemotingException, MQBrokerException, InterruptedException </span>&#123;</span><br><span class="line">    <span class="comment">// 寻找broker地址</span></span><br><span class="line">    <span class="keyword">long</span> beginStartTime = System.currentTimeMillis();</span><br><span class="line">    String brokerAddr = <span class="keyword">this</span>.mQClientFactory.findBrokerAddressInPublish(mq.getBrokerName());</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">null</span> == brokerAddr) &#123;</span><br><span class="line">        tryToFindTopicPublishInfo(mq.getTopic());</span><br><span class="line">        brokerAddr = <span class="keyword">this</span>.mQClientFactory.findBrokerAddressInPublish(mq.getBrokerName());</span><br><span class="line">    &#125;</span><br><span class="line">    SendMessageContext context = <span class="keyword">null</span>;</span><br><span class="line">    <span class="keyword">if</span> (brokerAddr != <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="comment">// 兼容低版本的配置</span></span><br><span class="line">        brokerAddr = MixAll.brokerVIPChannel(<span class="keyword">this</span>.defaultMQProducer.isSendMessageWithVIPChannel(), brokerAddr);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">byte</span>[] prevBody = msg.getBody();</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">//for MessageBatch,ID has been set in the generating process</span></span><br><span class="line">            <span class="keyword">if</span> (!(msg <span class="keyword">instanceof</span> MessageBatch)) &#123;</span><br><span class="line">                MessageClientIDSetter.setUniqID(msg);</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">int</span> sysFlag = <span class="number">0</span>;</span><br><span class="line">            <span class="keyword">boolean</span> msgBodyCompressed = <span class="keyword">false</span>;</span><br><span class="line">            <span class="keyword">if</span> (<span class="keyword">this</span>.tryToCompressMessage(msg)) &#123;</span><br><span class="line">                sysFlag |= MessageSysFlag.COMPRESSED_FLAG;</span><br><span class="line">                msgBodyCompressed = <span class="keyword">true</span>;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">final</span> String tranMsg = msg.getProperty(MessageConst.PROPERTY_TRANSACTION_PREPARED);</span><br><span class="line">            <span class="keyword">if</span> (tranMsg != <span class="keyword">null</span> &amp;&amp; Boolean.parseBoolean(tranMsg)) &#123;</span><br><span class="line">                sysFlag |= MessageSysFlag.TRANSACTION_PREPARED_TYPE;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">if</span> (hasCheckForbiddenHook()) &#123;</span><br><span class="line">                CheckForbiddenContext checkForbiddenContext = <span class="keyword">new</span> CheckForbiddenContext();</span><br><span class="line">                checkForbiddenContext.setNameSrvAddr(<span class="keyword">this</span>.defaultMQProducer.getNamesrvAddr());</span><br><span class="line">                checkForbiddenContext.setGroup(<span class="keyword">this</span>.defaultMQProducer.getProducerGroup());</span><br><span class="line">                checkForbiddenContext.setCommunicationMode(communicationMode);</span><br><span class="line">                checkForbiddenContext.setBrokerAddr(brokerAddr);</span><br><span class="line">                checkForbiddenContext.setMessage(msg);</span><br><span class="line">                checkForbiddenContext.setMq(mq);</span><br><span class="line">                checkForbiddenContext.setUnitMode(<span class="keyword">this</span>.isUnitMode());</span><br><span class="line">                <span class="keyword">this</span>.executeCheckForbiddenHook(checkForbiddenContext);</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">if</span> (<span class="keyword">this</span>.hasSendMessageHook()) &#123;</span><br><span class="line">                context = <span class="keyword">new</span> SendMessageContext();</span><br><span class="line">                context.setProducer(<span class="keyword">this</span>);</span><br><span class="line">                context.setProducerGroup(<span class="keyword">this</span>.defaultMQProducer.getProducerGroup());</span><br><span class="line">                context.setCommunicationMode(communicationMode);</span><br><span class="line">                context.setBornHost(<span class="keyword">this</span>.defaultMQProducer.getClientIP());</span><br><span class="line">                context.setBrokerAddr(brokerAddr);</span><br><span class="line">                context.setMessage(msg);</span><br><span class="line">                context.setMq(mq);</span><br><span class="line">                String isTrans = msg.getProperty(MessageConst.PROPERTY_TRANSACTION_PREPARED);</span><br><span class="line">                <span class="keyword">if</span> (isTrans != <span class="keyword">null</span> &amp;&amp; isTrans.equals(<span class="string">"true"</span>)) &#123;</span><br><span class="line">                    context.setMsgType(MessageType.Trans_Msg_Half);</span><br><span class="line">                &#125;</span><br><span class="line"></span><br><span class="line">                <span class="keyword">if</span> (msg.getProperty(<span class="string">"__STARTDELIVERTIME"</span>) != <span class="keyword">null</span> || msg.getProperty(MessageConst.PROPERTY_DELAY_TIME_LEVEL) != <span class="keyword">null</span>) &#123;</span><br><span class="line">                    context.setMsgType(MessageType.Delay_Msg);</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="keyword">this</span>.executeSendMessageHookBefore(context);</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            SendMessageRequestHeader requestHeader = <span class="keyword">new</span> SendMessageRequestHeader();</span><br><span class="line">            requestHeader.setProducerGroup(<span class="keyword">this</span>.defaultMQProducer.getProducerGroup());</span><br><span class="line">            requestHeader.setTopic(msg.getTopic());</span><br><span class="line">            requestHeader.setDefaultTopic(<span class="keyword">this</span>.defaultMQProducer.getCreateTopicKey());</span><br><span class="line">            requestHeader.setDefaultTopicQueueNums(<span class="keyword">this</span>.defaultMQProducer.getDefaultTopicQueueNums());</span><br><span class="line">            requestHeader.setQueueId(mq.getQueueId());</span><br><span class="line">            requestHeader.setSysFlag(sysFlag);</span><br><span class="line">            requestHeader.setBornTimestamp(System.currentTimeMillis());</span><br><span class="line">            requestHeader.setFlag(msg.getFlag());</span><br><span class="line">            requestHeader.setProperties(MessageDecoder.messageProperties2String(msg.getProperties()));</span><br><span class="line">            requestHeader.setReconsumeTimes(<span class="number">0</span>);</span><br><span class="line">            requestHeader.setUnitMode(<span class="keyword">this</span>.isUnitMode());</span><br><span class="line">            requestHeader.setBatch(msg <span class="keyword">instanceof</span> MessageBatch);</span><br><span class="line">            <span class="keyword">if</span> (requestHeader.getTopic().startsWith(MixAll.RETRY_GROUP_TOPIC_PREFIX)) &#123;</span><br><span class="line">                String reconsumeTimes = MessageAccessor.getReconsumeTime(msg);</span><br><span class="line">                <span class="keyword">if</span> (reconsumeTimes != <span class="keyword">null</span>) &#123;</span><br><span class="line">                    requestHeader.setReconsumeTimes(Integer.valueOf(reconsumeTimes));</span><br><span class="line">                    MessageAccessor.clearProperty(msg, MessageConst.PROPERTY_RECONSUME_TIME);</span><br><span class="line">                &#125;</span><br><span class="line"></span><br><span class="line">                String maxReconsumeTimes = MessageAccessor.getMaxReconsumeTimes(msg);</span><br><span class="line">                <span class="keyword">if</span> (maxReconsumeTimes != <span class="keyword">null</span>) &#123;</span><br><span class="line">                    requestHeader.setMaxReconsumeTimes(Integer.valueOf(maxReconsumeTimes));</span><br><span class="line">                    MessageAccessor.clearProperty(msg, MessageConst.PROPERTY_MAX_RECONSUME_TIMES);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            SendResult sendResult = <span class="keyword">null</span>;</span><br><span class="line">            <span class="keyword">switch</span> (communicationMode) &#123;</span><br><span class="line">                <span class="keyword">case</span> ASYNC:</span><br><span class="line">                    Message tmpMessage = msg;</span><br><span class="line">                    <span class="keyword">if</span> (msgBodyCompressed) &#123;</span><br><span class="line">                        <span class="comment">//If msg body was compressed, msgbody should be reset using prevBody.</span></span><br><span class="line">                        <span class="comment">//Clone new message using commpressed message body and recover origin massage.</span></span><br><span class="line">                        <span class="comment">//Fix bug:https://github.com/apache/rocketmq-externals/issues/66</span></span><br><span class="line">                        tmpMessage = MessageAccessor.cloneMessage(msg);</span><br><span class="line">                        msg.setBody(prevBody);</span><br><span class="line">                    &#125;</span><br><span class="line">                    <span class="keyword">long</span> costTimeAsync = System.currentTimeMillis() - beginStartTime;</span><br><span class="line">                    <span class="keyword">if</span> (timeout &lt; costTimeAsync) &#123;</span><br><span class="line">                        <span class="keyword">throw</span> <span class="keyword">new</span> RemotingTooMuchRequestException(<span class="string">"sendKernelImpl call timeout"</span>);</span><br><span class="line">                    &#125;</span><br><span class="line">                    sendResult = <span class="keyword">this</span>.mQClientFactory.getMQClientAPIImpl().sendMessage(</span><br><span class="line">                        brokerAddr,</span><br><span class="line">                        mq.getBrokerName(),</span><br><span class="line">                        tmpMessage,</span><br><span class="line">                        requestHeader,</span><br><span class="line">                        timeout - costTimeAsync,</span><br><span class="line">                        communicationMode,</span><br><span class="line">                        sendCallback,</span><br><span class="line">                        topicPublishInfo,</span><br><span class="line">                        <span class="keyword">this</span>.mQClientFactory,</span><br><span class="line">                        <span class="keyword">this</span>.defaultMQProducer.getRetryTimesWhenSendAsyncFailed(),</span><br><span class="line">                        context,</span><br><span class="line">                        <span class="keyword">this</span>);</span><br><span class="line">                    <span class="keyword">break</span>;</span><br><span class="line">                <span class="keyword">case</span> ONEWAY:</span><br><span class="line">                <span class="keyword">case</span> SYNC:</span><br><span class="line">                    <span class="keyword">long</span> costTimeSync = System.currentTimeMillis() - beginStartTime;</span><br><span class="line">                    <span class="keyword">if</span> (timeout &lt; costTimeSync) &#123;</span><br><span class="line">                        <span class="keyword">throw</span> <span class="keyword">new</span> RemotingTooMuchRequestException(<span class="string">"sendKernelImpl call timeout"</span>);</span><br><span class="line">                    &#125;</span><br><span class="line">                    sendResult = <span class="keyword">this</span>.mQClientFactory.getMQClientAPIImpl().sendMessage(</span><br><span class="line">                        brokerAddr,</span><br><span class="line">                        mq.getBrokerName(),</span><br><span class="line">                        msg,</span><br><span class="line">                        requestHeader,</span><br><span class="line">                        timeout - costTimeSync,</span><br><span class="line">                        communicationMode,</span><br><span class="line">                        context,</span><br><span class="line">                        <span class="keyword">this</span>);</span><br><span class="line">                    <span class="keyword">break</span>;</span><br><span class="line">                <span class="keyword">default</span>:</span><br><span class="line">                    <span class="keyword">assert</span> <span class="keyword">false</span>;</span><br><span class="line">                    <span class="keyword">break</span>;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">if</span> (<span class="keyword">this</span>.hasSendMessageHook()) &#123;</span><br><span class="line">                context.setSendResult(sendResult);</span><br><span class="line">                <span class="keyword">this</span>.executeSendMessageHookAfter(context);</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">return</span> sendResult;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (RemotingException e) &#123;</span><br><span class="line">            <span class="keyword">if</span> (<span class="keyword">this</span>.hasSendMessageHook()) &#123;</span><br><span class="line">                context.setException(e);</span><br><span class="line">                <span class="keyword">this</span>.executeSendMessageHookAfter(context);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">throw</span> e;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (MQBrokerException e) &#123;</span><br><span class="line">            <span class="keyword">if</span> (<span class="keyword">this</span>.hasSendMessageHook()) &#123;</span><br><span class="line">                context.setException(e);</span><br><span class="line">                <span class="keyword">this</span>.executeSendMessageHookAfter(context);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">throw</span> e;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">            <span class="keyword">if</span> (<span class="keyword">this</span>.hasSendMessageHook()) &#123;</span><br><span class="line">                context.setException(e);</span><br><span class="line">                <span class="keyword">this</span>.executeSendMessageHookAfter(context);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">throw</span> e;</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            msg.setBody(prevBody);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">throw</span> <span class="keyword">new</span> MQClientException(<span class="string">"The broker["</span> + mq.getBrokerName() + <span class="string">"] not exist"</span>, <span class="keyword">null</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<ol>
<li>由前面的brokerAddrTable寻找broker地址，找不到再尝试调用<strong>tryToFindTopicPublishInfo()</strong>走一遍之前的流程。</li>
<li>执行发送前后的hook，比如<strong>CheckForbiddenHook</strong>、<strong>SendMessageHook</strong>。</li>
<li>调用<strong>MQClientAPIImpl</strong>发送消息</li>
</ol>
<p>不管CommunicationMode是怎样其实消息发送调用的方法都是一样的，最终都是<strong>MQClientAPIImpl</strong>的<strong>sendMessage()</strong>，只是参数不同：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> SendResult <span class="title">sendMessage</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">    <span class="keyword">final</span> String addr,</span></span></span><br><span class="line"><span class="function"><span class="params">    <span class="keyword">final</span> String brokerName,</span></span></span><br><span class="line"><span class="function"><span class="params">    <span class="keyword">final</span> Message msg,</span></span></span><br><span class="line"><span class="function"><span class="params">    <span class="keyword">final</span> SendMessageRequestHeader requestHeader,</span></span></span><br><span class="line"><span class="function"><span class="params">    <span class="keyword">final</span> <span class="keyword">long</span> timeoutMillis,</span></span></span><br><span class="line"><span class="function"><span class="params">    <span class="keyword">final</span> CommunicationMode communicationMode,</span></span></span><br><span class="line"><span class="function"><span class="params">    <span class="keyword">final</span> SendMessageContext context,</span></span></span><br><span class="line"><span class="function"><span class="params">    <span class="keyword">final</span> DefaultMQProducerImpl producer</span></span></span><br><span class="line"><span class="function"><span class="params">)</span> <span class="keyword">throws</span> RemotingException, MQBrokerException, InterruptedException </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> sendMessage(addr, brokerName, msg, requestHeader, timeoutMillis, communicationMode, <span class="keyword">null</span>, <span class="keyword">null</span>, <span class="keyword">null</span>, <span class="number">0</span>, context, producer);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> SendResult <span class="title">sendMessage</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">    <span class="keyword">final</span> String addr,</span></span></span><br><span class="line"><span class="function"><span class="params">    <span class="keyword">final</span> String brokerName,</span></span></span><br><span class="line"><span class="function"><span class="params">    <span class="keyword">final</span> Message msg,</span></span></span><br><span class="line"><span class="function"><span class="params">    <span class="keyword">final</span> SendMessageRequestHeader requestHeader,</span></span></span><br><span class="line"><span class="function"><span class="params">    <span class="keyword">final</span> <span class="keyword">long</span> timeoutMillis,</span></span></span><br><span class="line"><span class="function"><span class="params">    <span class="keyword">final</span> CommunicationMode communicationMode,</span></span></span><br><span class="line"><span class="function"><span class="params">    <span class="keyword">final</span> SendCallback sendCallback,</span></span></span><br><span class="line"><span class="function"><span class="params">    <span class="keyword">final</span> TopicPublishInfo topicPublishInfo,</span></span></span><br><span class="line"><span class="function"><span class="params">    <span class="keyword">final</span> MQClientInstance instance,</span></span></span><br><span class="line"><span class="function"><span class="params">    <span class="keyword">final</span> <span class="keyword">int</span> retryTimesWhenSendFailed,</span></span></span><br><span class="line"><span class="function"><span class="params">    <span class="keyword">final</span> SendMessageContext context,</span></span></span><br><span class="line"><span class="function"><span class="params">    <span class="keyword">final</span> DefaultMQProducerImpl producer</span></span></span><br><span class="line"><span class="function"><span class="params">)</span> <span class="keyword">throws</span> RemotingException, MQBrokerException, InterruptedException </span>&#123;</span><br><span class="line">    <span class="keyword">long</span> beginStartTime = System.currentTimeMillis();</span><br><span class="line">    RemotingCommand request = <span class="keyword">null</span>;</span><br><span class="line">    <span class="keyword">if</span> (sendSmartMsg || msg <span class="keyword">instanceof</span> MessageBatch) &#123;</span><br><span class="line">        SendMessageRequestHeaderV2 requestHeaderV2 = SendMessageRequestHeaderV2.createSendMessageRequestHeaderV2(requestHeader);</span><br><span class="line">        request = RemotingCommand.createRequestCommand(msg <span class="keyword">instanceof</span> MessageBatch ? RequestCode.SEND_BATCH_MESSAGE : RequestCode.SEND_MESSAGE_V2, requestHeaderV2);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        request = RemotingCommand.createRequestCommand(RequestCode.SEND_MESSAGE, requestHeader);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    request.setBody(msg.getBody());</span><br><span class="line"></span><br><span class="line">    <span class="keyword">switch</span> (communicationMode) &#123;</span><br><span class="line">        <span class="keyword">case</span> ONEWAY:</span><br><span class="line">            <span class="keyword">this</span>.remotingClient.invokeOneway(addr, request, timeoutMillis);</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">        <span class="keyword">case</span> ASYNC:</span><br><span class="line">            <span class="keyword">final</span> AtomicInteger times = <span class="keyword">new</span> AtomicInteger();</span><br><span class="line">            <span class="keyword">long</span> costTimeAsync = System.currentTimeMillis() - beginStartTime;</span><br><span class="line">            <span class="keyword">if</span> (timeoutMillis &lt; costTimeAsync) &#123;</span><br><span class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> RemotingTooMuchRequestException(<span class="string">"sendMessage call timeout"</span>);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">this</span>.sendMessageAsync(addr, brokerName, msg, timeoutMillis - costTimeAsync, request, sendCallback, topicPublishInfo, instance,</span><br><span class="line">                retryTimesWhenSendFailed, times, context, producer);</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">        <span class="keyword">case</span> SYNC:</span><br><span class="line">            <span class="keyword">long</span> costTimeSync = System.currentTimeMillis() - beginStartTime;</span><br><span class="line">            <span class="keyword">if</span> (timeoutMillis &lt; costTimeSync) &#123;</span><br><span class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> RemotingTooMuchRequestException(<span class="string">"sendMessage call timeout"</span>);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">this</span>.sendMessageSync(addr, brokerName, msg, timeoutMillis - costTimeSync, request);</span><br><span class="line">        <span class="keyword">default</span>:</span><br><span class="line">            <span class="keyword">assert</span> <span class="keyword">false</span>;</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>具体如何发送消息先不说了，这个留待remoting模块。</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/RocketMQ之旅/" rel="tag"># RocketMQ之旅</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/10/08/Netty之旅（十二）EventLoop/" rel="next" title="Netty之旅（十二）EventLoop">
                <i class="fa fa-chevron-left"></i> Netty之旅（十二）EventLoop
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/11/12/RocketMQ之旅（四）client之Consumer/" rel="prev" title="RocketMQ之旅（四）client之Consumer">
                RocketMQ之旅（四）client之Consumer <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">matrix</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives">
              
                  <span class="site-state-item-count">47</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                
                  <span class="site-state-item-count">19</span>
                  <span class="site-state-item-name">标签</span>
                
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#从官方示例开始"><span class="nav-number">1.</span> <span class="nav-text">从官方示例开始</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#启动Producer"><span class="nav-number">2.</span> <span class="nav-text">启动Producer</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#发送消息"><span class="nav-number">3.</span> <span class="nav-text">发送消息</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#tryToFindTopicPublishInfo寻找路由"><span class="nav-number">3.1.</span> <span class="nav-text">tryToFindTopicPublishInfo寻找路由</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#selectOneMessageQueue选择消息队列"><span class="nav-number">3.2.</span> <span class="nav-text">selectOneMessageQueue选择消息队列</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#sendKernelImpl发送消息核心"><span class="nav-number">3.3.</span> <span class="nav-text">sendKernelImpl发送消息核心</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">matrix</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.4</div>
<div class=BbeiAn-info">
  浙ICP备 -
  <a href="http://www.beian.miit.gov.cn">18040498号</a>
  </a>
</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  

    
      <script id="dsq-count-scr" src="https://luyun.disqus.com/count.js" async></script>
    

    
      <script type="text/javascript">
        var disqus_config = function () {
          this.page.url = 'http://yoursite.com/2018/10/25/RocketMQ之旅（三）client之Producer/';
          this.page.identifier = '2018/10/25/RocketMQ之旅（三）client之Producer/';
          this.page.title = 'RocketMQ之旅（三）client之Producer';
        };
        var d = document, s = d.createElement('script');
        s.src = 'https://luyun.disqus.com/embed.js';
        s.setAttribute('data-timestamp', '' + +new Date());
        (d.head || d.body).appendChild(s);
      </script>
    

  




	





  














  





  

  

  

  
  

  

  

  

</body>
</html>
